package com.yixun.qfbao.api.service.login.weapp;

import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.api.service.login.BaseLoginService;
import com.yixun.qfbao.enums.QfSmsTemplateEnum;
import com.yixun.qfbao.mapper.SubscriptionMapper;
import com.yixun.qfbao.mapper.WxBindMapper;
import com.yixun.qfbao.model.Subscription;
import com.yixun.qfbao.model.WxBind;
import com.yixun.qfbao.model.dto.PartnerInfoDto;
import com.yixun.qfbao.model.dto.SubscriptionDto;
import com.yixun.qfbao.model.dto.WxBindDto;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.SMSTypeEnum;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.xf.model.enums.AttetionStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zilong.liu
 * @date 2020-7-31
 * @desc
 *
 */
@Service("weappLoginService")
public class WeAppLoginService extends BaseLoginService{
	
	@Autowired
	PartnerInfoService partnerInfoService;
	@Autowired
	SubscriptionMapper subscriptionMapper;
	@Autowired
	WxBindMapper wxBindMapper;
	
	@Value("${defaultWeAppAgencyAppId}")
	private String defaultWeAppAgencyAppId;
	
	//按照type的顺序进行取值, 第一个是占位
	protected int[] validTime = new int[] {0, 1, 2, 3};
	/**
	 * 组装调用短信验证码发送发放的入参
	 */
	@Override
	protected Map<String, Object> packSendParams(String type) {
		String code = Integer.toString(new Random().nextInt(900000)+100000);
		String messageContent = "";
		String msgId = "";
		String smsDesc = "";
		String[] msgs = null;
		switch (type) {
		case "1":
			messageContent = "您的短信验证码是" + code + "，本短信用于系统登录，有效时间" + validTime[Integer.parseInt(type)] + "分钟，请勿泄漏。";
			msgId = QfSmsTemplateEnum.SMS_LOGIN.getId();
			smsDesc = SMSTypeEnum.TYPE_14.getDes();
			msgs = new String[] {code, String.valueOf(validTime[Integer.parseInt(type)])};
			break;
		case "3":
			messageContent = "您的短信验证码是" + code + ",本条短信用于新用户注册，请勿泄露。";
			msgId = QfSmsTemplateEnum.SMS_REGISTER_USER.getId();
			smsDesc = SMSTypeEnum.TYPE_14.getDes();
			msgs = new String[] {code};
			break;
		case "2":
			messageContent = "您的短信验证码是" + code +",本条短信用于用户修改密码，有效时间" + validTime[Integer.parseInt(type)] + "分钟，请勿泄露。";
			msgId = QfSmsTemplateEnum.SMS_EDIT_PWD.getId();
			smsDesc = SMSTypeEnum.TYPE_14.getDes();
			msgs = new String[] {code, String.valueOf(validTime[Integer.parseInt(type)])};
			break;
		case "4":
			messageContent = "您的短信验证码是" + code + ",本条短信用于新用户注册，请勿泄露。";
			msgId = QfSmsTemplateEnum.SMS_REGISTER_USER.getId();
			smsDesc = SMSTypeEnum.TYPE_14.getDes();
			msgs = new String[] {code};
			break;
		default:
			break;
		}
		String systemId = SystemIdEnum.WEAPP_AGENCY.getCode();
		Map<String, Object> sendParams = new HashMap<>();
		sendParams.put("messageContent", messageContent);
		sendParams.put("msgId", msgId);
		sendParams.put("smsDesc", smsDesc);
		sendParams.put("code", code);
		sendParams.put("systemId", systemId);
		sendParams.put("msgs", msgs);
		return sendParams;
	}
	
	/**
	 * 更新openId信息
	 * 包括1、partner表中的unionId更新
	 */
	@Override
	public String updateOpenIdInfo(JSONObject wxBindInfoJson, String partnerId, String devCompanyUuid,
			String enableWeappMsg) {
		String weAppOpenId = wxBindInfoJson.getString("openid");
		Object unionId = wxBindInfoJson.get("unionid");
		// 获取当前公司对应的appId
		PartnerInfoDto piDto = new PartnerInfoDto();
		piDto.setId(Long.parseLong(partnerId));
		piDto.setWeappOpenid(weAppOpenId == null? "": weAppOpenId.toString());
		piDto.setUnionId(unionId == null? "": unionId.toString());
		if(!"1".equals(enableWeappMsg)) {
			partnerInfoService.update(piDto); 
			return null;
		}
		piDto.setLastLoginSystemId(SystemIdEnum.WEAPP_AGENCY.getCode());
		if(unionId == null) {
			partnerInfoService.update(piDto); 
			return null;
		}
		// 如果存在unionId，确保未绑定的厂商不会查找以及更新wxOpenId字段
		// 1、查找对应的appID
		SubscriptionDto subscriptionDto = new SubscriptionDto();
		subscriptionDto.setCompanyUuid(devCompanyUuid);
		List<String> systemIds = new ArrayList<>();
//		systemIds.add(SystemIdEnum.AGENCY_h5.getCode());
		systemIds.add(SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode());
//		systemIds.add(SystemIdEnum.AGENCY_h5.getCode());
		subscriptionDto.setSystemIds(systemIds);
//		subscriptionDto.setOrders(" t.system_id desc ");
		subscriptionDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<Subscription> subscriptionList = subscriptionMapper.selectListByDto(subscriptionDto);
		// 没配置时，则只更新unionId,weappopenId
		if(CollectionUtils.isEmpty(subscriptionList)) {
			partnerInfoService.update(piDto); 
			return null;
		}
		// 2、从表tm_wx_bind查找对应的wxOpenId。查找appId,如果一个公司有多个公众号。分销小程序以分销助手优先
		WxBindDto wxBindDto = new WxBindDto();
		wxBindDto.setAppId(subscriptionList.get(0).getAppId());
		wxBindDto.setUnionId(unionId.toString());
		wxBindDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<WxBind> wxbindList = wxBindMapper.list(wxBindDto, 0, 1);
		//没关注时，则只更新unionId,weappopenId
		if(CollectionUtils.isEmpty(wxbindList)) {
			partnerInfoService.update(piDto); 
			return null;
		}
		// 3、更新表中的partnerId
		// 如果是取消关注，则需要更新为空，如果是关注，则更新为关注表的数据
		String attetionStatus = wxbindList.get(0).getAttentionStatus();
		String openId = "";
		if(AttetionStatusEnum.set_attetion.getNo().toString().equals(attetionStatus)) {
			openId = wxbindList.get(0).getWxOpenId();
		}
		// 4、设置对应的wxOpenId，以让partner_info更新
		piDto.setWxOpenid(openId);
		partnerInfoService.update(piDto); 
		// 根据appId，以及appSecret 更新对应的partnerId
		Long wxBindId = wxbindList.get(0).getId();
		WxBindDto updateWxBindDto = new WxBindDto();
		updateWxBindDto.setPartnerId(Long.parseLong(partnerId));
		updateWxBindDto.setId(wxBindId);
		updateWxBindDto.setWeappOpenId(weAppOpenId);
		wxBindMapper.edit(updateWxBindDto);
		return openId;
	}
	
	
	/**
	 * 获取所有可登录的companyUuid
	 * 	1、客户定制版本，是前端传入，无需改变
	 * 	2、闪卖通用版本，所有配置成使用闪卖登录的商家均可以登录
	 * @param companyUuids
	 * @return
	 */
	@Override
	public List<String> getAllCompanyUuid (List<String> companyUuids, String loginType){
		// 1、 传入非空，则使用前台传递的
		if(!CollectionUtils.isEmpty(companyUuids)) {
			return companyUuids;
		}
		// 2、传入为空，则查询为闪卖对应的所有公司UUID
		SubscriptionDto subscriptionDto = new SubscriptionDto();
		subscriptionDto.setAppId(defaultWeAppAgencyAppId);
		subscriptionDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		subscriptionDto.setSystemId(loginType);
		List<Subscription> subscriptionList = subscriptionMapper.selectListByDto(subscriptionDto);
		if(CollectionUtils.isEmpty(subscriptionList)) {
			return null;
		}
		return subscriptionList.stream().map(Subscription:: getCompanyUuid).collect(Collectors.toList());
	}
	
}
